//
//  MyCollectionViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/8/16.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "MyCollectionViewController.h"
#import "NOContentView.h"
#import "MyCollectionCell.h"
#import "NOContentView.h"
@interface MyCollectionViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;

/**
 编辑
 */
@property (nonatomic, strong) UIButton *rightBtn;

/**
 删除
 */
@property (nonatomic, strong) UIButton *deleteBtn;

/**
 全选
 */
@property (nonatomic, strong) UIButton *allBtn;
@property (nonatomic, strong) NSMutableArray *selectArray;

@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)NSMutableArray *dataArray;

@end

@implementation MyCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavagationBackBtn];
    self.title = @"我的收藏";
//    [self createTabelveiew];
    [self setupChildViews];
    UIImageView *placeImageView = [[UIImageView alloc] init];
    [self.view addSubview:placeImageView];
    placeImageView.image = [UIImage imageNamed:@"collectionzhanwei"];
    [placeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(215), scaleTopAndBottom(278)));
        make.centerY.equalTo(self.view.mas_centerY).offset(scaleTopAndBottom(10));
    }];
    
//    NOContentView *noconteView = [NOContentView initWithImage:@"collectionzhanwei" AndWithTitile:@""];
//    noconteView.frame = self.view.bounds;
//    [self.view addSubview:noconteView];
//    [self getAllData];
//    NOContentView *nocnetView = [NOContentView initWithImage:@"订单无数据" AndWithTitile:@"这里啥也没有☺"];
//    nocnetView.frame = self.view.bounds;
//    [self.view addSubview:nocnetView];
    
    // Do any additional setup after loading the view.
}
-(void)createNavagationBackBtn{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 6, 67, 23);
    UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigator_btn_back"]];
    backImg.frame = CGRectMake(-10, 0, 22, 22);
    [backBtn addSubview:backImg];
    UILabel *backText = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 65, 22)];
//    backText.text = @"返回";
    backText.font = [UIFont systemFontOfSize:17];
    [backText setBackgroundColor:[UIColor clearColor]];
    [backText setTextColor:[UIColor whiteColor]];
    [backBtn addSubview:backText];
    [backBtn addTarget:self action:@selector(leftBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
    [backImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_left).offset(-10);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    [backText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backImg.mas_right).offset(2);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(65, 22));
    }];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    [self.navigationItem setLeftBarButtonItem:leftButton];
}
-(void)leftBarButtonItemPressed:(UIButton *)btn{
    [UIView animateWithDuration:0.1 animations:^{
        [_bottomView removeFromSuperview];
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)createTabelveiew{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[MyCollectionCell class] forCellReuseIdentifier:@"MyCollectionCell"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCollectionCell"];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return scaleTopAndBottom(12) * 2 + 72;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    }
}
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma makr - 删除功能的实现
- (void)setupChildViews {
    UIBarButtonItem *spatce = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    UIBarButtonItem *rightBaritem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    spatce.width = -10;
    self.navigationItem.rightBarButtonItems = @[spatce,rightBaritem];
    
}

- (void)rightBtnAction {
    self.rightBtn.selected = !self.rightBtn.isSelected;
    self.deleteBtn.hidden = !self.rightBtn.isSelected;
    self.allBtn.hidden = !self.rightBtn.isSelected;
    if (self.rightBtn.isSelected) {
        [self.tableView setEditing:YES animated:YES];
        [self showBottomUI];
    }else{
        [self.tableView setEditing:NO animated:YES];
        [self removebackView];
    }
}

- (void)deleteBtnAction {
    NSMutableArray<NSIndexPath *> *indexArr = [NSMutableArray array];
    for (int i = 0; i < self.selectArray.count; i++) {
//        NSInteger index = [self.dataArray indexOfObject:self.selectArray[i]];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [indexArr addObject:indexPath];
    }
    
    // 不能写在上面的for循环里面
    
    [self.selectArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if ([self.dataArray containsObject:obj] ) {
//            [self.dataArray removeObject:obj];
//        }
    }];
    
    [self.selectArray removeAllObjects];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView deleteRowsAtIndexPaths:indexArr withRowAnimation:UITableViewRowAnimationNone];
    });
}

- (void)allBtnAction {
    self.allBtn.selected = !self.allBtn.isSelected;
    self.rightBtn.selected = self.allBtn.isSelected;
    if (self.allBtn.isSelected) {
        
        NSArray<NSIndexPath *> *arr = self.tableView.indexPathsForVisibleRows;
        [self.selectArray removeAllObjects];
//        [self.selectArray addObjectsFromArray:self.dataArray];
        for (NSIndexPath *indexPath in arr) {
            [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        }
    }
//    else{
//        [self.selectArray removeAllObjects];
//        [self.tableView setEditing:NO];
//        self.allBtn.hidden = YES;
//        self.deleteBtn.hidden = YES;
//    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSNumber *select = self.dataArray[indexPath.row];
//    if (![self.selectArray containsObject:select]) {
//        [self.selectArray addObject:select];
//    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSNumber *select = self.dataArray[indexPath.row];
//    if ([self.selectArray containsObject:select]) {
//        [self.selectArray removeObject:select];
//    }
}
- (UIButton *)rightBtn {
    if (!_rightBtn) {
        _rightBtn = [[UIButton alloc] init];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [_rightBtn setTitle:@"完成" forState:UIControlStateSelected];
        
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_rightBtn sizeToFit];
    }
    return _rightBtn;
}

- (UIButton *)deleteBtn {
    if (!_deleteBtn) {
        _deleteBtn = [[UIButton alloc] init];
        _deleteBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        
        [_deleteBtn setTitleColor:[UIColor whiteColor] forState:0];
        [_deleteBtn setBackgroundColor:[UIColor redColor]];
        [_deleteBtn addTarget:self action:@selector(deleteBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_deleteBtn sizeToFit];
        _deleteBtn.hidden = YES;
    }
    return _deleteBtn;
}

- (UIButton *)allBtn {
    if (!_allBtn) {
        _allBtn = [[UIButton alloc] init];
        _allBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_allBtn setTitle:@"全选" forState:UIControlStateNormal];
//        [_allBtn setTitle:@"取消" forState:UIControlStateSelected];
        
        [_allBtn setTitleColor:[UIColor blackColor] forState:0];
//        [_allBtn setTitleColor:[UIColor blueColor] forState:1];
        
        [_allBtn addTarget:self action:@selector(allBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_allBtn sizeToFit];
        _allBtn.hidden = YES;
    }
    return _allBtn;
}

-(void)showBottomUI{
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, 49)];
    [self setUIAbovewView:_bottomView];
    [[UIApplication sharedApplication].keyWindow addSubview:_bottomView];
    _bottomView.backgroundColor = [UIColor whiteColor];
    [UIView animateWithDuration:0.1 animations:^{
        _bottomView.frame = CGRectMake(0,HEIGHT - 49, WIDTH, 49);
    }];
}
-(void)removebackView{
    
    [UIView animateWithDuration:0.1 animations:^{
        [_bottomView removeFromSuperview];
    }];
}
-(void)setUIAbovewView:(UIView *)view{
    UIImageView *imageView = [[UIImageView alloc] init];
    [view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view.mas_left).offset(12);
        make.size.mas_equalTo(CGSizeMake(16, 16));
    }];
    [view addSubview:self.deleteBtn];
    [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(view);
        make.width.mas_equalTo(85);
    }];
    [view addSubview:self.allBtn];
    [self.allBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(view);
        make.width.mas_equalTo(85);
    }];
}
-(void)getAllData{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/matchApp/matchCollectList";
    NSString *sessionID = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSDictionary *parma = [NSDictionary dictionaryWithObjectsAndKeys:sessionID,@"sessionId", nil];
    [manager POST:url parameters:parma progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"收藏信息%@",jsonDic);
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
